package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author stone
 * @date 2022/04/27 11:48
 */
@Service
public class AccountServiceImpl implements AccountService{

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    TransactionTemplate template;


    @Override
    public void transfer(Integer fromId, Integer destId, Integer money) {
        Integer execute = template.execute(new TransactionCallback<Integer>() {
            @Override
            public Integer doInTransaction(TransactionStatus transactionStatus) {
                Integer fromMoney = accountMapper.queryMoneyByPrimaryKey(fromId);
                Integer destMoney = accountMapper.queryMoneyByPrimaryKey(destId);

                fromMoney -= money;
                destMoney += money;

                accountMapper.updateMoneyByPrimaryKey(fromId, fromMoney);
                int i = 1 / 0;
                accountMapper.updateMoneyByPrimaryKey(destId, destMoney);
                return 5;//doInTransaction返回值是多少，execute的值就是多少
            }
        });

    }
}
